import { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import apis from "../../apis/login";
import useMeStore from "../../store/me";

interface UseLoginReturn {
  phone: string;
  setPhone: (value: string) => void;
  vcode: string;
  setVcode: (value: string) => void;
  countdown: number;
  error: string;
  isLoading: boolean;
  handleSendVcode: () => Promise<void>;
  handleLogin: () => Promise<void>;
  handleSubmit: (e: React.FormEvent) => void;
}

export const useLogin = (): UseLoginReturn => {
  const navigate = useNavigate();
  const [phone, setPhone] = useState("");
  const [vcode, setVcode] = useState("");
  const [dkey, setDkey] = useState("");
  const [countdown, setCountdown] = useState(0);
  const [error, setError] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const meStore = useMeStore();

  // 验证手机号格式
  const isValidPhone = (phone: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  };

  // 发送验证码
  const handleSendVcode = async (): Promise<void> => {
    if (!isValidPhone(phone)) {
      setError("请输入正确的手机号码");
      return;
    }

    setError("");
    setIsLoading(true);

    try {
      const result = await apis.loginSendVcode({ phone });
      setDkey(result);
      setCountdown(60);
      startCountdown();
      setError("验证码发送成功");
    } catch (err) {
      setError("验证码发送失败，请重试");
      console.error("发送验证码失败:", err);
    } finally {
      setIsLoading(false);
    }
  };

  // 开始倒计时
  const startCountdown = (): void => {
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 处理登录
  const handleLogin = async (): Promise<void> => {
    if (!isValidPhone(phone)) {
      setError("请输入正确的手机号码");
      return;
    }

    if (!vcode) {
      setError("请输入验证码");
      return;
    }

    if (!dkey) {
      setError("请先获取验证码");
      return;
    }

    setError("");
    setIsLoading(true);

    try {
      const me = await apis.login({ phone, vcode, dkey });
      meStore.afterLogin(me);
      // 登录成功后跳转到首页或其他页面
      alert("登录成功");
      navigate("/"); // 使用 react-router 进行页面跳转
    } catch (err) {
      setError("登录失败，请检查手机号和验证码是否正确");
      console.error("登录失败:", err);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent): void => {
    e.preventDefault();
    handleLogin();
  };

  // 组件卸载时清理定时器
  useEffect(() => {
    // 这里不需要额外的清理，因为我们在 setCountdown 的回调中已经清除了定时器
    return () => {
      // 组件卸载时的清理工作
    };
  }, []);

  return {
    phone,
    setPhone,
    vcode,
    setVcode,
    countdown,
    error,
    isLoading,
    handleSendVcode,
    handleLogin,
    handleSubmit,
  };
};
